import {
  Controller,
  Post,
  Body,
  Get,
  UploadedFile,
  UseInterceptors,
  Res,
  HttpException
} from '@nestjs/common';
// import { UploadService } from './upload.service';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiOperation, ApiTags, ApiBearerAuth } from '@nestjs/swagger';
import { join } from 'path';
import { UserService } from '../system/user/user.service';
import type { Response } from 'express';

@ApiTags('文件上传模块')
@ApiBearerAuth() // 添加BearerAuth装饰器
@Controller('upload')
export class UploadController {
  // constructor(private readonly uploadService: UploadService) {}
  constructor(private readonly userService: UserService) {}
  @ApiOperation({ summary: '照片上传' })
  @Post('/avatar')
  @UseInterceptors(
    //文件上传拦截器
    FileInterceptor('file', {
      limits: { fileSize: 1024 * 1024 * 2 } // 限制文件大小为2M
    })
  )
  async upload(@UploadedFile() file: Express.Multer.File, @Body() body: any) {
    if (!file) {
      throw new HttpException('上传失败', 400);
    }
    const { userId } = body;
    if (!userId) {
      throw new HttpException('缺少用户id', 400);
    }
    await this.userService.update(userId, { avatar: file.filename });
    return { url: file.filename, size: file.size };
  }

  @ApiOperation({ summary: '照片下载' })
  @Get('export')
  downLoad(@Res() res: Response) {
    const url = join(__dirname, 'dist', '../images');
    res.download(url);
  }
}
